//
//  CoreDateManager.m
//  
//
//  Created by shaorui on 15/10/19.
//
//

#import "CoreDateManager.h"

static CoreDateManager * _coreDateManager;
@implementation CoreDateManager

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;


#pragma life cycle
+(CoreDateManager *)shareCoreDateManager
{
    @synchronized(self){  //为了确保多线程情况下，仍然确保实体的唯一性
        
        if (!_coreDateManager)
            {
                //该方法会调用 allocWithZone
            _coreDateManager = [[CoreDateManager alloc] init];
            }
    }
    return  _coreDateManager;
}


+(id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
    if (!_coreDateManager)
        {
        _coreDateManager = [super allocWithZone:zone]; //确保使用同一块内存地址
        return _coreDateManager;
        }
    }
    
    return nil;
}
-(BOOL)saveContextBool
{
    

AppDelegate *deleaget = ((AppDelegate*)[[UIApplication sharedApplication] delegate]);
        
        NSManagedObjectContext *managedObjectContext = deleaget.managedObjectContext;

    BOOL noSave = NO;
    NSError *error = nil;
    
    if (managedObjectContext != nil) {
        
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            noSave = NO;

            abort();
        }
        else
            {
                noSave = YES;
            
            }
    }
    return noSave;
}
- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext * managedObjectContext = self.managedObjectContext;
    
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Core Data stack

    // Returns the managed object context for the application.
    // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.

//管理对象，上下文，持久性存储模型对象
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

    // Returns the managed object model for the application.
    // If the model doesn't already exist, it is created from the application's model.
//被管理的数据模型，数据结构
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreData__Demo" withExtension:@"momd"];
    
#warning modelURL 文件路径
    
    NSLog(@"%@",modelURL);
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

    // Returns the persistent store coordinator for the application.
    // If the coordinator doesn't already exist, it is created and the application's store added to it.

//连接数据库的
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData__Demo.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

    // Returns the URL to the application's Documents directory.获取Documents路径
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

    //插入多条数数据
- (void)insertCoreData:(NSMutableArray*)dataArray
{    AppDelegate *deleaget = ((AppDelegate*)[[UIApplication sharedApplication] delegate]);

    NSManagedObjectContext *context =  [self managedObjectContext];
//    NSEntityDescription *entity = [NSEntityDescription entityForName:@"USER_INFO" inManagedObjectContext:context];

//    for ( int i=0;i<[dataArray count];i++)
//    {
//    USER_INFO * newsInfo  = [dataArray objectAtIndex:i];
////     newsInfo = [NSEntityDescription insertNewObjectForEntityForName:TableName inManagedObjectContext:context];
//
//
//    }
    
    NSError *error;
    if(![context save:&error])
        {
        NSLog(@"不能保存：%@",[error localizedDescription]);
        }
}

    //插入多条数数据
- (void)insertUserInfoCoreData:(USER_INFO*)info

{
    
    AppDelegate *deleaget = ((AppDelegate*)[[UIApplication sharedApplication] delegate]);

    NSManagedObjectContext *context = deleaget.managedObjectContext;

//        USER_INFO *newsInfo = [NSEntityDescription insertNewObjectForEntityForName:@"USER_INFO" inManagedObjectContext:context];
//        newsInfo = info;
//        newsInfo.userName = info.userName;
//        newsInfo.userAge = info.userAge;
//        newsInfo.userID = info.userID;
//        newsInfo.userSex = info.userSex;
//        
        NSError *error;
        if(![context save:&error])
            {
                NSLog(@"不能保存：%@",[error localizedDescription]);
            }
}
    //查询
- (NSMutableArray*)selectData:(int)pageSize andOffset:(int)currentPage
{
    
    
    NSManagedObjectContext *context = [self managedObjectContext];
    
        // 限定查询结果的数量
        //setFetchLimit
        // 查询的偏移量
        //setFetchOffset
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"USER_INFO"];
    
/*
 NSFetchRequest 常用方法
 -setEntity:
 设置你要查询的数据对象的类型（Entity）
 -setPredicate:
 设置查询条件
 -setFetchLimit:
 设置最大查询对象数目
 -setSortDescriptors:
 设置查询结果的排序方法
 -setAffectedStores:
 设置可以在哪些数据存储中查询
 
 */
//    [fetchRequest setFetchLimit:pageSize];
//    [fetchRequest setFetchOffset:currentPage];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"USER_INFO" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    
    NSError *error;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    NSMutableArray *resultArray = [NSMutableArray array];
    
    for (USER_INFO *info in fetchedObjects) {
        
        NSLog(@" USER_INFO :%@", info);

        NSLog(@"userName:%@", info.userName);
        NSLog(@"userAge:%@", info.userAge);
        NSLog(@"userID:%@", info.userID);

        [resultArray addObject:info];
    }
    return resultArray;
}

    //删除
-(void)deleteData
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"USER_INFO" inManagedObjectContext:context];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setIncludesPropertyValues:NO];
    [request setEntity:entity];
    NSError *error = nil;
    NSArray *datas = [context executeFetchRequest:request error:&error];
    if (!error && datas && [datas count])
        {
        for (NSManagedObject *obj in datas)
            {
            [context deleteObject:obj];
            }
        if (![context save:&error])
            {
            NSLog(@"error:%@",error);
            }
        }
}
    //更新
- (void)updateData:(NSString*)newsId  withIsLook:(NSString*)islook
{
    NSManagedObjectContext *context = [self managedObjectContext];
    
//    NSPredicate *predicate = [NSPredicate
//                              predicateWithFormat:@"newsid like[cd] %@",newsId];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"newsid like[cd] %@",newsId];
    
        //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:TableName inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    
        //https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];//这里获取到的是一个数组，你需要取出你要更新的那个obj
    for (USER_INFO *info in result) {
        info.userName = islook;
    }
    
        //保存
    if ([context save:&error]) {
            //更新成功
        NSLog(@"更新成功");
    }
}

    //清理用户信息
-(BOOL)ClearUserInfo
{
    __block BOOL bResult = NO;
    
    [[self managedObjectContext] performBlock:^
     {
     NSError *error = nil;
     NSArray *arrReturn = nil;
     
         //创建取回数据请求
     NSFetchRequest *request = [[NSFetchRequest alloc] init];
         //设置要检索哪种类型的实体对象
     NSEntityDescription *entity = [NSEntityDescription entityForName:@"USER_INFO" inManagedObjectContext:self.managedObjectContext];
     
     [request setEntity:entity];//设置请求实体
     
     
     arrReturn = [self.managedObjectContext executeFetchRequest:request error:&error];
     if (error == nil)
         {
         bResult = YES;
             //删除旧数据
         if ( [arrReturn count] > 0  && [[arrReturn objectAtIndex:0] isKindOfClass:[USER_INFO class]])
             {
             for (NSManagedObject *object in arrReturn)
                 {
                 
                 [self.managedObjectContext deleteObject:object];
                 }
             }
         }
     
     [self saveContext];
     
     }];
    
    
    
    return bResult;
}
- (BOOL)deleteUserInfoCoreData:(USER_INFO*)deleteinfo
{
    
    BOOL delete = NO;
    
    NSManagedObjectContext *context = [self managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"USER_INFO" inManagedObjectContext:context];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setIncludesPropertyValues:NO];
    [request setEntity:entity];
    NSError *error = nil;
    NSArray *datas = [context executeFetchRequest:request error:&error];
    
    
    if (!error && datas && [datas count])
        {
        for (USER_INFO *obj in datas)
            {
            
            
            if (obj.userID.integerValue == deleteinfo.userID.integerValue) {
                [context deleteObject:obj];
                NSLog(@"已删除 deleteinfodeleteinfodeleteinfodeleteinfo");
                break;
            }

            }
        if (![context save:&error])
            {
            delete = NO;
            NSLog(@"error:%@",error);
            }
        else
            delete = YES;
        }

    return delete;

}

@end
